﻿using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Derbster.Peer
{
    public class VectorClock
    {
        private static Dictionary<string, int> _clockDictionary;
        public VectorClock()
        {
            if (_clockDictionary == null)
            {
                _clockDictionary = new Dictionary<string, int> { { PeerContext.PeerId, 0 } };
            }
        }

        public int GetVersion()
        {
            return _clockDictionary[PeerContext.PeerId];
        }

        public void Increment()
        {
            lock (_clockDictionary)
            {
                _clockDictionary[PeerContext.PeerId] += 1;
            }
        }

        public void MergeReceived(string recievedVectorClockString)
        {
            var receivedVectorClock = recievedVectorClockString.Split(',').Select(
                s =>
                    {
                        var entry = s.Split(':');
                        return new { PeerId = entry[0], TimeStamp = Int32.Parse(entry[1]) };
                    }).ToList();

            var time = GetVersion();
            foreach (var receivedClock in receivedVectorClock)
            {
                var otherPeerId = receivedClock.PeerId;
                if (!_clockDictionary.ContainsKey(otherPeerId))
                {
                    _clockDictionary.Add(otherPeerId, receivedClock.TimeStamp);
                }
                _clockDictionary[otherPeerId] = (receivedClock.TimeStamp > time) ? receivedClock.TimeStamp : time;
            }
        }

        public override string ToString()
        {
            var stringList = new List<String>();
            lock (_clockDictionary)
            {
                stringList.AddRange(_clockDictionary.Select(clock => clock.Key + ":" + clock.Value));
            }
            return String.Join(",", stringList);
        }
    }
}
